package com.zhugang.week05;

import java.util.HashSet;
import java.util.Set;

/**
 * @program algorithms
 * @description: removeDuplicateNodes
 * @author: chanzhugang
 * @create: 2022/07/08 14:34
 */
public class RemoveDuplicateNodes {

    /**
     * 面试题 02.01 移除重复节点
     *
     * @param head
     * @return
     */
    public ListNode removeDuplicateNodes(ListNode head) {
        // 开辟新链表、尾插 + 哈希表缓存
        ListNode newNode = new ListNode(-1);
        ListNode tail = newNode;
        ListNode p = head;
        Set<Integer> set = new HashSet<>();
        while (p != null) {
            ListNode temp = p.next;
            if (!set.contains(p.val)) {
                set.add(p.val);

                tail.next = p;
                tail = p;
                tail.next = null;
            }
            p = temp;
        }
        return newNode.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}